import { Plugin, TFile, Notice, Editor, EditorPosition } from "obsidian";
import fs from "fs";
import { sep } from "path";

export default class ObsidianDelImgMenuPlugin extends Plugin {
	async onload() {
		console.log("加载图片删除插件");
		// 注册右键菜单
		this.registerEvent(
			this.app.workspace.on("editor-menu", (menu, editor, view) => {
				const cursor = editor.getCursor();
				const line = editor.getLine(cursor.line);

				const imagePath = this.extractImagePath(line);
				if (imagePath) {
					// 添加删除选项到右键菜单
					menu.addItem((item) => {
						item.setTitle("删除图片")
							.setIcon("trash")
							.onClick(async () => {
								try {
									// 获取图片文件
									const filePath = this.getCurrentNotePath();
									if (filePath) {
										const file = this.convertToSystemPath(
											filePath + "\\" + imagePath
										);
										new Notice(file);

										fs.unlink(file, (error) => {
											if (error) {
												new Notice(
													`删除图片失败: ${error.message}`
												);
											} else {
												this.removeAllImageReferences(
													editor,
													imagePath
												);
												new Notice(
													`删除图片成功！`
												);
											}
										});
									}
								} catch (error) {
									new Notice(
										`删除图片失败: ${error.message}`
									);
								}
							});
					});
				}
			})
		);
	}

	private convertToSystemPath(path: string): string {
		if (sep !== "/") {
			return path.replace(/\//g, sep);
		}
		return path;
	}

	// 从Markdown行中提取图片路径
	private extractImagePath(text: string): string | null {
		// 匹配标准Markdown图片格式 ![](path)
		let match = text.match(/!\[[^\]]*\]\(([^)]+)\)/);
		if (match) {
			return match[1].trim();
		}

		// 匹配Obsidian内部链接格式 ![[path]]
		match = text.match(/!\[\[([^\|\]]+)/);
		if (match) {
			return match[1].trim();
		}

		return null;
	}

	// 删除编辑器中所有的图片引用
	private removeAllImageReferences(editor: Editor, imagePath: string) {
		const escapedPath = imagePath.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
		const mdRegex = new RegExp(`!?\\[[^\\]]*\\]\\(${escapedPath}\\)`, "g");
		const obsidianRegex = new RegExp(
			`!?\\[\\[${escapedPath}(\\|.*?)?\\]\\]`,
			"g"
		);

		let updatedContent = editor.getValue();

		// 替换所有标准Markdown格式的图片引用
		if (mdRegex.test(updatedContent)) {
			updatedContent = updatedContent.replace(mdRegex, "");
		}

		// 替换所有Obsidian内部链接格式的图片引用
		if (obsidianRegex.test(updatedContent)) {
			updatedContent = updatedContent.replace(obsidianRegex, "");
		}

		// 设置更新后的内容
		editor.setValue(updatedContent);
	}

	private getCurrentNotePath(): string | null {
		let attachmentPath = (this.app.vault as any).config
			.attachmentFolderPath;
		if (attachmentPath) {
			attachmentPath = attachmentPath.replace("./", "");
		} else {
			attachmentPath = "attachmentPath";
		}

		const basePath = (this.app.vault.adapter as any).getBasePath();

		// 获取当前活动文件
		const activeFile = this.app.workspace.getActiveFile();

		if (activeFile instanceof TFile) {
			return (
				basePath +
				"\\" +
				activeFile.path.replace("/" + activeFile.name, "") +
				"\\" +
				attachmentPath
			);
		}

		return null;
	}
}
